<template>
  <div class="group_main">
    <con-title :topTitle="topTitle" />

    <el-card class="box-card controls_con">
      <div class="con">
        <div>
          <span>群组名称:</span>
          <el-input
            placeholder="群组名称"
            v-model="groupName"
            style="width: 200px"
          ></el-input>
          <el-button type="primary" @click="getGroupByID">搜索</el-button
          >&nbsp;&nbsp;&nbsp;<span>搜索结果: {{ groupData.total }}</span>
        </div>

        <el-button type="primary" @click="addGroup"
          >新增群组 <span class="iconfont">&#xe604;</span></el-button
        >
      </div>
    </el-card>

    <el-card class="box-card">
      <div class="table_con">
        <el-table class="table" :data="nowPageData.data" style="width: 100%">
          <el-table-column prop="index" width="50"> </el-table-column>
          <el-table-column prop="groupName" label="群组名称" width="180">
            <template slot-scope="scope">
              {{
                scope.row.groupName == undefined
                  ? scope.row.name
                  : scope.row.groupName
              }}
            </template>
          </el-table-column>
          <el-table-column prop="nodeNums" label="传感器节点数量" width="180">
          </el-table-column>
          <el-table-column prop="onlineNums" label="在线设备数量">
          </el-table-column>
          <el-table-column prop="cTime" label="创建时间"> </el-table-column>
          <el-table-column label="操作" >
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="rename(scope.row)"
                >重命名</el-button
              >
              <el-button type="text" size="small" @click="del(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination_center">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="currentChange"
            :page-sizes="[5, 10, 15]"
            :page-size="pageSize"
            :current-page="currPage"
            layout="total, sizes, prev, pager, next, jumper"
            :total="groupData.total"
          >
          </el-pagination>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import ConTitle from "@/components/ConTitle.vue";
import {
  $getGroupList,
  $getGroupByID,
  $addGroup,
  $rename,
  $delGroup,
} from "@/api/api.js";

export default {
  name: "group",
  components: {
    ConTitle,
  },
  data() {
    return {
      topTitle: {
        type: "设备",
        text: "节点群组",
        msg: "以分组的形式管理节点设备，提供了搜索、添加新的群组、重命名、移动设备等功能。",
      },
      groupName: "",
      allList: [], //存全部数据
      groupData: [], //存拷贝的
      nowPageData: [], //渲染用
      currPage: 1, //第几页
      pageSize: 5,
    };
  },
  filters: {
    Time(val) {
      let date = new Date(val);
      let year = date.getFullYear();
      let month = fillZero(date.getMonth() + 1);
      let day = fillZero(date.getDate());
      let h = fillZero(date.getHours());
      let m = fillZero(date.getMinutes());
      let s = fillZero(date.getSeconds());
      function fillZero(v) {
        return v < 10 ? "0" + v : v;
      }
      return `${year}-${month}-${day} ${h}:${m}:${s}`;
    },
  },
  created() {
    this.getGroupList();
  },
  methods: {
    handleSizeChange(index) {
      this.pageSize = index;
      this.currPage = 1;
      if (this.groupName != "") {
        this.getGroupList();
      }
    },

    currentChange(index) {
      console.log("ue", index);
      this.page(index);
    },

    getGroupByID() {
      if (this.groupName == "") {
        //空处理
        this.groupData = JSON.parse(JSON.stringify(this.allList));
        this.page(1);
        return;
      }
      let flag = true;
      this.allList.data.forEach((val) => {
        if (val.groupName == this.groupName) {
          flag = false;
          $getGroupByID(val.id).then((res) => {
            console.log("单个组：", res);
            this.groupData = {
              total: 1,
              data: [res.data.data],
            };
            this.nowPageData = this.groupData;
            this.currPage = 1;
          });
        }
      });
      if (flag) {
        //没有查找到，给个空数据
        this.nowPageData = this.groupData = {
          total: 0,
          data: [],
        };
      }
      this.groupName = "";
    },

    addGroup() {
      this.$prompt("", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /[^]+/,
        inputErrorMessage: "请输入内容",
      })
        .then(({ value }) => {
          $addGroup(value).then(() => {
            this.$message({
              type: "success",
              message: "添加成功:" + value,
            });
            //展示不自动更新了
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消添加",
          });
        });
    },

    rename(row) {
      //重命名，重命名请求接口，成功后修改渲染的值，并不再次请求接口获取新数据
      console.log("重命名", row);
      this.$prompt("", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /[^]+/,
        inputValue: row.groupName ? row.groupName : row.name,
        inputErrorMessage: "请输入内容",
      })
        .then(({ value }) => {
          $rename(row.id, value).then(() => {
            //更新
            this.allList.data.forEach((e) => {
              if (row.id == e.id) {
                if (e.name) {
                  e.name = value;
                } else {
                  e.groupName = value;
                }
              }
            });
            this.groupData.data.forEach((e) => {
              if (row.id == e.id) {
                if (e.name) {
                  e.name = value;
                } else {
                  e.groupName = value;
                }
              }
            });
            this.nowPageData.data.forEach((e) => {
              if (row.id == e.id) {
                if (e.name) {
                  e.name = value;
                } else {
                  e.groupName = value;
                }
              }
            });
            this.$message({
              type: "success",
              message: "成功修改:",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消修改",
          });
        });
    },

    del(row) {
      //删除也一样，只修改渲染的值，注意可能存在删除后后面的行往前面排，这样才合理
      console.log("删除", row);
      this.$confirm("此操作将永久删除该群组, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          $delGroup(row.id).then(() => {
            this.allList.data.forEach((e, index) => {
              if (row.id == e.id) {
                this.allList.data.splice(index, 1);
                this.allList.total--;
                this.indexRefresh(this.allList.data);
              }
            });
            this.groupData.data.forEach((e, index) => {
              if (row.id == e.id) {
                this.groupData.data.splice(index, 1);
                this.groupData.total--;
                this.indexRefresh(this.groupData.data);
              }
            });
            this.nowPageData.data.forEach((e, index) => {
              if (row.id == e.id) {
                this.nowPageData.data.splice(index, 1);
                if (index + 1 < this.nowPageData.total) {
                  //代表后面还有数据，进行推进
                  this.nowPageData.data.push(this.groupData.data[e.index - 1]);
                }
                this.nowPageData.total--;
                //刷新当前页面
                this.page(this.currPage);
              }
            });
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    indexRefresh(obj) {
      //刷新index序号
      obj.forEach((e, index) => {
        e.index = index + 1;
      });
    },

    getGroupList() {
      //流程是，先请求一个全部数据作为查询用不干扰该数据的内容完整，然后在一个groupData里修改
      $getGroupList().then((res) => {
        console.log("群组：", res);
        res.data.data = res.data.data.map((val, index) => {
          val.index = index + 1 + (this.currPage - 1) * this.pageSize;
          return val;
        });
        this.allList = JSON.parse(JSON.stringify(res.data));
        this.groupData = res.data;
        //默认翻到当前页
        this.page(this.currPage);
      });
    },

    //翻页，取index页的数据
    page(index) {
      this.currPage = index;
      let _i = this.pageSize * (this.currPage - 1);
      let _j = this.pageSize * this.currPage;
      let data = this.groupData.data.slice(_i, _j);
      this.nowPageData = {
        data,
        total: data.length,
      };
    },
  },
};
</script>

<style scoped lang="scss">
.group_main::-webkit-scrollbar {
  display: none;
}
.group_main {
  width: 100%;
  height: 100%;
  overflow-y: scroll;

  > .controls_con {
    margin: 10px 0;
    width: 100%;
    .con {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: space-between;
      > div {
        height: 100%;
      }
      * {
        margin: 0px 5px;
      }
      .iconfont {
        color: white !important;
      }
      span:last-of-type {
        font-size: 14px;
        color: gray;
      }
    }
  }

  .pagination_center {
    text-align: center;
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: white;
  }
  .table_con {
    width: 100%;
    height: 100%;
  }
}
</style>